package com.owc.filter.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.owc.common.context.SessionHelper;
import com.owc.common.custom.annotation.Advice;
import com.owc.common.enums.ClientEnum;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonInputMessage;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * Request for conduct params encrypt
 */
@Component
@ControllerAdvice(basePackages = "com.owc.controller")
@Slf4j
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {

    private static final String PARAM_KEY = "data";

    /**
     * If return false. any request not adopt this. use true express request will enter interceptor
     * @param methodParameter Method's params string .
     * @param type            Type
     * @return  Pass-check
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {

        Advice advice = methodParameter.getParameterAnnotation(Advice.class);

        boolean needDecrypt = Boolean.parseBoolean(SessionHelper.getRequestHeader("decrypt").filter(s -> !s.isEmpty()).orElse("true"));

        if(!needDecrypt){
            log.info("No need to decrypt");
        }

        return needDecrypt && (advice== null || advice.need()) && methodParameter.getParameterAnnotation(RequestBody.class) != null;
    }

    /**
     * Send controller before interceptor operation
     * @return Data after decryption
     */
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        try {
            log.debug("Start handler request body. Content-type:[{}]",SessionHelper.getContextRequest().getHeader("Content-type"));
            //Encrypted string
            Object encrypted = parserParams(httpInputMessage);
            if(encrypted == null){
                return null;
            }
            log.info(">>>>> Raw encrypted param info: {}",encrypted);
            String decode = ClientEnum.findDecode(Integer.parseInt(clientType())).decodeAdvice().decode(encrypted);
            log.info("<<<<< DecodeRequestBodyAdvice decode params info: {}",decode);

            if (Objects.equals("error", decode)) {
                log.error(">>>>> Failed to decrypt request header data <<<<<");
                //Decryption failed
                throw new BadRequestException(ExceptionEnum.PARAMS_DECRYPT_ERR);
            }

            return new MappingJacksonInputMessage(new ByteArrayInputStream(decode.getBytes(StandardCharsets.UTF_8)),httpInputMessage.getHeaders());
        } catch (IOException ex) {
            log.error("DecodeRequestBodyAdvice execute fail !!!!! {}", ex.getMessage());
            throw ex;
        } catch (Exception e){
            log.error("Unusual execution decryption !!!!! {}",e.getMessage());
        }
        return null;
    }

    private String clientType(){
        return SessionHelper.getContextRequest().getHeader("client");
    }

    private Object parserParams(HttpInputMessage httpInputMessage) {
        String clientType = clientType();

        Assert.notNull(clientType,"Client type must not be null");

        log.info("Process http request. Client type is:[{}]",clientType);
        Optional<ClientEnum> optionalClientEnum = ClientEnum.match(Integer.parseInt(clientType));

        if(!optionalClientEnum.isPresent()){
            log.error("Match client enum failed. Current request client type:[{}]",clientType);
            return null;
        }

        switch (optionalClientEnum.get()){
            case ANDROID:
            case IOS:
                return getAppDataBuff(httpInputMessage);
            case WEB:
                return parserWebParams(httpInputMessage);
            default:
                return null;
        }
    }

    private String parserWebParams(HttpInputMessage httpInputMessage) {

        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader;
        JSONObject paramsObj;

        try {
            InputStream inputStream = httpInputMessage.getBody();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }

            //Original request params
            paramsObj = JSON.parseObject(stringBuilder.toString());
            return paramsObj.getString(PARAM_KEY);
        }catch (Exception e){
            log.error("Parser WEB request params failed. message:[{}]",e.getMessage());
            log.error("Throw exception stack: \n" );
            throw new BadRequestException("Parser request params failed.");
        }
    }

    private static byte[] getAppDataBuff(HttpInputMessage httpInputMessage) {
        HttpServletRequest request = SessionHelper.getContextRequest();
        try {
            int contentLength = request.getContentLength();
            InputStream inputStream = httpInputMessage.getBody();
            if (contentLength < 0) {
                return null;
            }
            byte[] buffer = new byte[contentLength];
            for (int i = 0; i < contentLength; ) {

                int readlen = inputStream.read(buffer, i,
                        contentLength - i);
                if (readlen == -1) {
                    break;
                }
                i += readlen;
            }
            if (buffer.length == 0) {
                return null;
            }
            log.debug("原始byte数组：{}" , Arrays.toString(buffer));
            log.debug("原始String：{}",new String(buffer, StandardCharsets.UTF_8));
            return buffer;
        } catch (Exception e) {
            log.error(JSON.toJSONString(e.getStackTrace()));
            throw new BadRequestException("Parser request params failed.");
        }
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return null;
    }
}
